import {ElMessage} from "element-plus";
import config from "./config";

export default {
    getQueryVariable(variable) {
        var query = window.location.search.substring(1)
        var vars = query.split("&")
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=")
            if (pair[0] === variable) {
                return pair[1]
            }
        }
        return false
    },
    isMobile(str) {
        let rule = /^1\d{10}$/
        return rule.test(str)
    },
    padLeftZero(str) {
        return ('00' + str).substr(str.length)
    },
    formatDate(unix_timestamp, fmt = 'yyyy-MM-dd hh:mm:ss') {
        let date = new Date(unix_timestamp * 1000)
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        }
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + ''
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str))
            }
        }
        return fmt
    },

    checkImage(file, maxsize = 512) {
        if (file.size > maxsize * 1024) {
            ElMessage.error('图片大小不能超过' + maxsize + 'Kb')
            return false
        }
        let filename = file.name
        let arr = filename.split('.')
        let ext = arr.length > 1 ? arr.pop() : ''
        let allowType = ['image/jpeg', 'image/bmp', 'image/gif', 'image/png', 'image/jpg', 'image/pjpeg', 'image/x-png', 'image/webp']
        if (allowType.indexOf(file.type) === -1) {
            ElMessage.error('不支持的文件类型:' + file.type)
            return false
        }
        return ext
    },

    clearLocalStorage() {
        let tmpObj = JSON.parse(JSON.stringify(localStorage))		// 深拷贝
        for (let key in tmpObj) {
            let reg = new RegExp("^" + config.cache_prefix, "g");
            if (reg.test(key) === true) {
                localStorage.removeItem(key)
                // console.log(key)
                // console.log('已删除')
            }
        }
    },
    setLocalStorage(key, value) {
        localStorage.setItem(config.cache_prefix + '_' + key, value);
    },
    getLocalStorage(key) {
        return localStorage.getItem(config.cache_prefix + '_' + key);
    },
    obj2Form(obj) {
        let formData = new FormData()
        if (typeof obj === "object") {
            for (let key in obj) {
                formData.append(key, obj[key])
            }
        }
        return formData
    },
    editorHandleFill(content) {
        if (content != null) {
            let reg = new RegExp("<img src=\"wangeditor/", "g");
            content = content.replace(reg, "<img src=\"" + config.editorPath + "wangeditor/")
        }
        return content;
    },
    editorHandleTrim(content) {
        if (content != null) {
            let reg = new RegExp("<img src=\"" + config.editorPath, "g");
            content = content.replace(reg, "<img src=\"")
        }
        return content;
    },

    validateHexString(hexString) {
		hexString = hexString.toUpperCase()
        if(hexString.length%2 === 1) {
            return false
        }
        return /^([0-9A-Fa-f]+)$/.test(hexString);
    },
    hexToBytes(hex) {
        const bytes = [];
        if (hex.length % 2 === 1) {
            return bytes
        }
        for (let i = 0; i < hex.length; i += 2) {
            bytes.push(parseInt(hex.substr(i, 2), 16));
        }
        return bytes
    },
    bytesToHex(bytes) {
        return bytes.map(byte => byte.toString(16).padStart(2, '0')).join('');
    }

}
